import django_filters
from django_filters.rest_framework import DjangoFilterBackend, FilterSet

from mysqldb.models import *


class ListDjangoFilterBackend(DjangoFilterBackend):
    """自己定义过滤器"""

    def get_schema_fields(self, view):
        if view.action not in ["list"]:
            return []
        return super().get_schema_fields(view)


# print(dir(django_filters.ChoiceFilter))


class ReqsnFilter(FilterSet):
    mtype = django_filters.ChoiceFilter(
        field_name="message_type",
        choices=[("order", "销售单"), ("refund", "退货单")],
        label="订单类型",
        required=False,
    )
    wbid = django_filters.CharFilter(
        field_name="wb_id",
        label="场所ID",
        required=False,
    )
    pay_type = django_filters.CharFilter(
        field_name="pay_type",
        label="支付方式",
        required=False,
    )
    order_type = django_filters.CharFilter(
        field_name="order_type",
        label="订单类型",
        required=False,
    )
    order_status = django_filters.CharFilter(
        field_name="order_status",
        label="订单状态",
        required=False,
    )
    stardate = django_filters.DateTimeFilter(
        field_name="create_time",
        method="filter_stardate",
        label="开始日期",
        required=False,
    )
    enddate = django_filters.DateTimeFilter(
        field_name="create_time",
        method="filter_enddate",
        label="结束日期",
        required=False,
    )

    def filter_stardate(self, qs, name, value):
        lookup = "__".join([name, "gte"])
        return qs.filter(**{lookup: value})

    def filter_enddate(self, qs, name, value):
        lookup = "__".join([name, "lte"])
        return qs.filter(**{lookup: value})

    class Meta:
        model = FsygShopreqsnList
        fields = ["mtype", "wbid", "pay_type", "order_type", "stardate", "enddate"]
        # fields = "__all__"
